<template>
  <div class="video-detail-container">
    <!-- 顶部导航 -->
    <div class="video-header">
      <el-icon class="back-btn" :size="24" @click="goBack">
        <ArrowLeft />
      </el-icon>
      <h1 class="page-title">视频详情</h1>
    </div>
    
    <!-- 加载中状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <div class="loading-text">加载中...</div>
    </div>
    
    <!-- 视频内容 -->
    <div v-else-if="videoInfo" class="video-content">
      <!-- 视频播放器 -->
      <div class="video-player-container">
        <VideoPlayer
          :video-url="videoInfo.videoUrl"
          :cover-url="videoInfo.coverUrl"
          :autoplay="true"
          :show-controls="true"
          @play="handlePlay"
          @pause="handlePause"
          @ended="handleEnded"
        />
      </div>
      
      <!-- 视频信息 -->
      <div class="video-info-section">
        <!-- 作者信息 -->
        <div class="author-info" @click="goToUserProfile">
          <UserAvatar
            :user-id="videoInfo.author?.id"
            :avatar-url="videoInfo.author?.avatar"
            :username="videoInfo.author?.username"
            :nickname="videoInfo.author?.nickname"
            size="large"
            :clickable="true"
            @click="goToUserProfile"
          />
          <div class="author-details">
            <h3 class="author-name">{{ videoInfo.author?.nickname || '用户' }}</h3>
            <p class="author-desc">{{ videoInfo.author?.signature || '这个人很懒，什么都没有留下...' }}</p>
          </div>
        </div>
        
        <!-- 视频标题和描述 -->
        <div class="video-meta">
          <h2 class="video-title">{{ videoInfo.title }}</h2>
          <p v-if="videoInfo.description" class="video-description">
            {{ videoInfo.description }}
          </p>
          <div class="video-stats">
            <span class="stat-item">
              <el-icon><View /></el-icon>
              {{ formatCount(videoInfo.viewCount) }} 播放
            </span>
            <span class="stat-item">
              <el-icon><Timer /></el-icon>
              {{ formatTime(videoInfo.createdAt) }}
            </span>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <div class="action-btn" :class="{ active: isLiked }" @click="toggleLike">
            <el-icon :size="24">
              <StarFilled v-if="isLiked" />
              <Star v-else />
            </el-icon>
            <span class="action-count">{{ formatCount(videoInfo.likeCount) }}</span>
            <span class="action-label">点赞</span>
          </div>
        </div>
      </div>
      
      <!-- 相关视频 -->
      <div class="related-videos">
        <h3 class="section-title">相关推荐</h3>
        <div class="related-list">
          <div
            v-for="video in relatedVideos"
            :key="video.id"
            class="related-item"
            @click="playRelatedVideo(video)"
          >
            <div class="related-cover">
              <img :src="video.coverUrl" :alt="video.title" />
              <div class="related-duration">
                {{ formatDuration(video.duration) }}
              </div>
            </div>
            <div class="related-info">
              <h4 class="related-title">{{ video.title }}</h4>
              <p class="related-author">{{ video.author?.nickname }}</p>
              <div class="related-stats">
                <span>{{ formatCount(video.viewCount) }} 播放</span>
                <span>{{ formatCount(video.likeCount) }} 点赞</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-icon :size="60"><Warning /></el-icon>
      <div class="error-text">视频加载失败</div>
      <el-button type="primary" @click="loadVideoDetail">重新加载</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getVideoDetail, likeVideo, getRecommendVideos } from '@/api/video'
import { formatCount, formatTime, formatDuration } from '@/utils'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft, View, Timer,
  Star, StarFilled, Warning
} from '@element-plus/icons-vue'
import VideoPlayer from '@/components/VideoPlayer/index.vue'
import UserAvatar from '@/components/UserAvatar/index.vue'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const loading = ref(true)
const videoInfo = ref(null)
const relatedVideos = ref([])

// 交互状态
const isLiked = ref(false)

// 加载视频详情
const loadVideoDetail = async () => {
  const videoId = route.params.id
  
  if (!videoId) {
    ElMessage.error('视频ID无效')
    goBack()
    return
  }
  
  try {
    loading.value = true
    
    // 获取视频详情
    const response = await getVideoDetail(videoId)
    videoInfo.value = response.data
    
    console.log('视频详情数据:', videoInfo.value)
    console.log('作者信息:', videoInfo.value.author)
    
    // 如果没有作者信息但有userId，尝试获取作者信息
    if (!videoInfo.value.author && videoInfo.value.userId) {
      console.log('作者信息缺失，尝试通过userId获取:', videoInfo.value.userId)
      try {
        // 使用userStore的fetchUserAvatar方法获取头像
        const avatarUrl = await userStore.fetchUserAvatar(videoInfo.value.userId)
        console.log('获取到的头像URL:', avatarUrl)
        
        // 设置作者信息
        videoInfo.value.author = {
          id: videoInfo.value.userId,
          username: `user_${videoInfo.value.userId}`, // 临时用户名
          nickname: '用户', // 默认昵称
          avatar: avatarUrl && avatarUrl !== '/default-avatar.svg' ? avatarUrl.replace('http://localhost:3000', '') : '',
          signature: '这个人很懒，什么都没有留下...'
        }
        console.log('设置后的作者信息:', videoInfo.value.author)
      } catch (error) {
        console.warn('获取作者信息失败:', error)
        // 设置默认作者信息
        videoInfo.value.author = {
          id: videoInfo.value.userId,
          username: `user_${videoInfo.value.userId}`,
          nickname: '用户',
          avatar: '',
          signature: '这个人很懒，什么都没有留下...'
        }
      }
    }
    
    // 模拟获取相关视频
    const relatedResponse = await getRecommendVideos({ current: 1, size: 10 })
    relatedVideos.value = relatedResponse.data.records.filter(v => v.id !== videoId).slice(0, 6)
    
    // 设置初始状态
    isLiked.value = videoInfo.value.isLiked || false
    
  } catch (error) {
    ElMessage.error('加载视频失败')
    console.error('加载视频详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 视频播放事件
const handlePlay = () => {
  console.log('视频开始播放')
}

const handlePause = () => {
  console.log('视频暂停')
}

const handleEnded = () => {
  console.log('视频播放结束')
}

// 点赞视频
const toggleLike = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }

  try {
    await likeVideo(videoInfo.value.id)
    isLiked.value = !isLiked.value
    videoInfo.value.likeCount += isLiked.value ? 1 : -1
    ElMessage.success(isLiked.value ? '点赞成功' : '取消点赞')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 播放相关视频
const playRelatedVideo = (video) => {
  router.push(`/video/${video.id}`)
}

// 跳转到用户主页
const goToUserProfile = () => {
  if (videoInfo.value?.author?.id) {
    router.push(`/user/${videoInfo.value.author.id}`)
  }
}

// 返回上一页
const goBack = () => {
  if (window.history.length > 1) {
    router.go(-1)
  } else {
    router.push('/')
  }
}

// 组件挂载
onMounted(() => {
  loadVideoDetail()
})
</script>

<style lang="scss" scoped>
.video-detail-container {
  width: 100vw;
  min-height: 100vh;
  background: $bg-light;
  overflow-x: hidden;
}

.video-header {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: $text-white;
  border-bottom: 1px solid $border-light;
  
  .back-btn {
    cursor: pointer;
    color: $text-dark;
    transition: $transition-fast;
    
    &:hover {
      transform: translateX(-2px);
    }
  }
  
  .page-title {
    flex: 1;
    text-align: center;
    font-size: 18px;
    font-weight: 600;
    margin: 0;
    color: $text-dark;
  }
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  gap: 16px;
  
  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid $border-light;
    border-top: 3px solid $primary-color;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  
  .loading-text,
  .error-text {
    color: $text-gray;
    font-size: 16px;
  }
  
  .el-icon {
    color: $text-gray;
  }
}

.video-content {
  .video-player-container {
    position: relative;
    width: 100%;
    max-width: 100vw;
    background: $bg-dark;
  }
  
  .video-info-section {
    background: $text-white;
    padding: 16px;
    margin-bottom: 8px;
    
    .author-info {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 16px;
      cursor: pointer;
      
      .author-details {
        flex: 1;
        
        .author-name {
          font-size: 16px;
          font-weight: 600;
          color: $text-dark;
          margin: 0 0 4px 0;
        }
        
        .author-desc {
          font-size: 12px;
          color: $text-gray;
          margin: 0;
        }
      }
    }
    
    .video-meta {
      margin-bottom: 16px;
      
      .video-title {
        font-size: 18px;
        font-weight: 600;
        color: $text-dark;
        margin: 0 0 8px 0;
        line-height: 1.4;
      }
      
      .video-description {
        font-size: 14px;
        color: $text-gray;
        line-height: 1.5;
        margin: 0 0 12px 0;
      }
      
      .video-stats {
        display: flex;
        gap: 16px;
        font-size: 12px;
        color: $text-gray;
        
        .stat-item {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
    
    .action-buttons {
      display: flex;
      gap: 20px;
      padding: 16px 0;
      border-top: 1px solid $border-light;
      
      .action-btn {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 4px;
        cursor: pointer;
        transition: $transition-fast;
        
        &:hover {
          transform: translateY(-2px);
        }
        
        &.active {
          color: $primary-color;
        }
        
        .action-count {
          font-size: 12px;
          font-weight: 600;
        }
        
        .action-label {
          font-size: 10px;
          color: $text-gray;
        }
      }
    }
  }
  
  .related-videos {
    background: $text-white;
    padding: 16px;
    margin-bottom: 8px;
    
    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: $text-dark;
      margin: 0 0 16px 0;
    }
    
    .related-list {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
      gap: 12px;
      
      .related-item {
        cursor: pointer;
        border-radius: $border-radius;
        overflow: hidden;
        transition: $transition-fast;
        
        &:hover {
          transform: translateY(-2px);
          box-shadow: $box-shadow-hover;
        }
        
        .related-cover {
          position: relative;
          width: 100%;
          height: 120px;
          background: $bg-gray;
          
          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          .related-duration {
            position: absolute;
            bottom: 6px;
            right: 6px;
            background: rgba(0, 0, 0, 0.7);
            color: $text-white;
            padding: 2px 4px;
            border-radius: 3px;
            font-size: 10px;
          }
        }
        
        .related-info {
          padding: 8px;
          
          .related-title {
            font-size: 12px;
            font-weight: 600;
            color: $text-dark;
            margin: 0 0 6px 0;
            line-height: 1.3;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
          
          .related-author {
            font-size: 10px;
            color: $text-gray;
            margin: 0 0 4px 0;
          }
          
          .related-stats {
            display: flex;
            gap: 8px;
            font-size: 10px;
            color: $text-gray;
          }
        }
      }
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 768px) {
  .video-content {
    .video-info-section {
      padding: 12px;
      
      .action-buttons {
        gap: 16px;
        
        .action-btn {
          .action-count {
            font-size: 11px;
          }
          
          .action-label {
            font-size: 9px;
          }
        }
      }
    }
    
    .related-videos {
      padding: 12px;
      
      .related-list {
        grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
        gap: 10px;
        
        .related-item .related-cover {
          height: 100px;
        }
      }
    }
  }
}
</style> 